import com.codezen.helper.Worker;
import com.codezen.util.DownloadHelper;

import flash.events.Event;
import flash.events.ProgressEvent;
import flash.filesystem.File;
import flash.media.Video;

import utils.anime.AniEpisode;

// ani download manage
private var adm:DownloadHelper;
// sub download manager
private var sdm:DownloadHelper;
private var cachedAniEp:AniEpisode;

private function initAniCaching():void{
	adm = new DownloadHelper(File.applicationStorageDirectory.resolvePath('downloads/').nativePath);
	adm.addEventListener(ProgressEvent.PROGRESS, cachingProgress);
	adm.addEventListener(Event.COMPLETE, cachingAniComplete);
	sdm = new DownloadHelper(File.applicationStorageDirectory.resolvePath('downloads/').nativePath);
}

private function delAniCachedEpisode(currentEpisode:AniEpisode):void{
	if(currentEpisode == null) return;
	
	// get filename
	var filename:String = currentEpisode.video;
	filename = filename.substring( filename.indexOf("[[local=")+8, filename.length-2 );
	
	// del file
	var file:File = new File(filename);
	file.deleteFile();
	
	// del sub
	file = new File( filename.replace(".mp4", ".srt") );
	file.deleteFile();
	
	// refresh
	adb.addEventListener(Event.COMPLETE, onAniCacheEventComplete);
	
	// remove from db
	if(currentEpisode.view == "true"){
		currentEpisode.video = String(currentEpisode.video).replace(/\[\[local=(.+?)\]\]/gs,"");
		adb.saveEpisode(currentEpisode);
	}else{
		adb.delEpisode(currentEpisode);
	}
	
	// refresh
	dbLoadSaveEpisodes();
}

private function cacheAniEpisode(ep:AniEpisode):void{
	if(ep == null) return;
	
	cache_wnd.visible = true;
	cache_episode_name.text = "Эпизод: "+ep.title+" [сезон "+ep.season+", эпизод "+ep.num+"]";
	cache_series_name.text = "Сериал: "+ep.serial_title;
	
	// save ep data
	cachedAniEp = ep;
	
	// get filename
	var res:Array = String(cachedAniEp.video).split("/");
	var file:String = res[res.length-1];
	
	// get subtitles
	if(cachedAniEp.sub1 == '1'){
		var sub:String = file.replace(".mp4",".srt");
		var subURL:String = "http://anime.tulavideo.net/"+cachedAniEp.serial_id+"/"+cachedAniEp.aid+"_1.srt";
		sdm.downloadFileFromServer(sub, subURL);
	}
	
	// download
	adm.downloadFileFromServer(file, cachedAniEp.video);
}

private function cachingAniComplete(e:Event):void{
	cachedAniEp.video = cachedAniEp.video +"[[local="+ adm.localPath + adm.filename+"]]";
	adb.addEventListener(Event.COMPLETE, onAniCacheEventComplete);
	adb.saveEpisode(cachedAniEp);
	
	cache_wnd.visible = false;
}

private function onAniCacheEventComplete(e:Event):void{
	adb.removeEventListener(Event.COMPLETE, onAniCacheEventComplete);
	// refresh
	dbLoadSaveEpisodes();
}